package com.woniu.service;

import com.alibaba.fastjson.JSON;
import com.woniu.adapter.NoticeRepositoryApater;
import com.woniu.adapter.UserRepositoryApater;
import com.woniu.adapter.transactionRecordsApater;
import com.woniu.exception.NoticeException;
import com.woniu.inlet.web.command.AddNoticeCommand;
import com.woniu.inlet.web.command.AddNoticeCommandHandle;
import com.woniu.outlet.mysql.po.Notice;
import com.woniu.outlet.mysql.po.NoticeExample;
import com.woniu.outlet.mysql.po.TransactionRecords;
import com.woniu.service.domain.UserDo;
import com.woniu.utils.AppUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Slf4j
@Service
@Transactional
public class NoticeService implements AddNoticeCommandHandle {
    @Autowired
    private NoticeRepositoryApater noticeRepositoryApater;
    @Autowired
    private UserRepositoryApater userRepositoryApater;
    @Autowired
    private transactionRecordsApater transactionRecordsApater;


    /*
    【基金，黄金的定投】买入业务
    1.根据flag判断定投订单生成是否成功，如果成功，执行扣钱，存消息表，存交易表；
    2.不成功，存消息表，用于通知用户
     */
    @Override
    public void addNotice(AddNoticeCommand command) {
        Notice notice = new Notice();
        if ("n".equals(command.getFlag())) {//定投失败 --余额不足
            notice.setFlag(command.getFlag());
            notice.setUserId(command.getUserId());//定投的用户id
            notice.setStatus("0");//未读的消息
            notice.setCreateTime(AppUtils.getNowTimeStr());//创建通知的时间
            notice.setContent(JSON.toJSONString(command.getFixedMsgVo()));//将定投定投详情对象
            noticeRepositoryApater.add(notice);//存通知
        } else { //flag 为 y ->扣钱 ，存交易记录，存通知
            //判断余额是否充足
            UserDo userDo = userRepositoryApater.getById(command.getUserId());
            if (userDo.getRestAmount().compareTo(command.getMoney()) == -1) {//余额小于定投金额
                notice.setFlag("n");
                notice.setUserId(command.getUserId());//定投的用户id
                notice.setStatus("0");//未读的消息
                notice.setCreateTime(AppUtils.getNowTimeStr());//创建通知的时间
                notice.setContent(JSON.toJSONString(command.getFixedMsgVo()));//将定投定投详情对象
                noticeRepositoryApater.add(notice);//存通知
                throw new NoticeException("余额不足，定投不成功");
            }

            //余额充足-->更新余额
            userDo.setRestAmount(userDo.getRestAmount().subtract(command.getMoney()));
            userRepositoryApater.updateInfo(userDo);

            //存通知
            notice.setFlag(command.getFlag());
            notice.setUserId(command.getUserId());//定投的用户id
            notice.setStatus("0");//未读的消息
            notice.setCreateTime(AppUtils.getNowTimeStr());//创建通知的时间
            notice.setContent(JSON.toJSONString(command.getFixedMsgVo()));//定投详情对象
            noticeRepositoryApater.add(notice);//存通知
            log.debug("黄金，基金的定投业务存储通知，通知对象为[{}]", notice);
            //存交易记录
            TransactionRecords transactionRecords = new TransactionRecords();
            transactionRecords.setMoney(new BigDecimal("-" + command.getMoney()));
            transactionRecords.setTime(AppUtils.getNowTimeStr());
            transactionRecords.setName(command.getFixedMsgVo().getName());
            transactionRecords.setType("buy");
            transactionRecords.setTypeId(command.getFixedMsgVo().getId().intValue());
            transactionRecordsApater.add(transactionRecords);
            log.debug("黄金，基金的定投业务存储通知，交易记录对象为[{}]", transactionRecords);
        }

    }

    //根据用户id查询该用户的通知（按时间先后是顺序）
    public List<Notice> getByUserId(Integer userId) {
        NoticeExample example = new NoticeExample();
        example.setOrderByClause("create_time DESC");
        example.or().andUserIdEqualTo(userId);
        List<Notice> notices = noticeRepositoryApater.getByUserId(example);
        return notices;
    }

    //根据Id修改通知状态
    public void updateById(Integer id) {
        Notice notice = noticeRepositoryApater.getById(id);
        if (notice == null) {
            throw new NoticeException("未查询到该通知消息");
        }
        notice.setStatus("1");
        noticeRepositoryApater.update(notice);
    }


}
